﻿using DoNetDrive.Protocol.Door.Door8800.Door.ReaderOption;
using DoNetDrive.Protocol.Door.Door8800.Door.RelayOption;
using DoNetDrive.Protocol.Door.Door8800.Door.Remote;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DoNetDrive.Protocol.Door.Door8800.Utility;
using DoNetDrive.Protocol.Door.Door8800.Door;
using System.Collections;
using DoNetDrive.Protocol.Door.Door8800.Door.ReaderWorkSetting;
using DoNetDrive.Core.Util;
using DoNetDrive.Protocol.Door.Door8800.Data.TimeGroup;
using DoNetDrive.Protocol.Door.Door8800.Door.DoorWorkSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.AutoLockedSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.RelayReleaseTime;
using System.Text.RegularExpressions;
using DoNetDrive.Protocol.Door.Door8800.Door.ReaderInterval;
using DoNetDrive.Protocol.Door.Test.Model;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.FunctionParameter;
using DoNetDrive.Protocol.Door.Door8800.Door.AntiPassback;
using DoNetDrive.Protocol.Door.Door8800.Door.PushButtonSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.AnyCardSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.VoiceBroadcastSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.InOutSideReadOpenSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.ManageKeyboardSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.AreaAntiPassback;
using DoNetDrive.Protocol.Door.Door8800.Door.InterLockSetting;
using DoNetDrive.Protocol.Door.Door8800.Door.MultiCard;
using DoNetDrive.Protocol.Door.Door8800.Door.ReaderAlarm;
using DoNetDrive.Protocol.Door.Door89H.Door.ReadCardAndTakePictures;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TCPSetting;

namespace DoNetDrive.Protocol.Door.Test
{
    public partial class frmDoor : frmNodeForm
    {
        #region 单例模式
        private static object lockobj = new object();
        private static frmDoor onlyObj;


        public static frmDoor GetForm(INMain main)
        {
            if (onlyObj == null)
            {
                lock (lockobj)
                {
                    if (onlyObj == null)
                    {
                        onlyObj = new frmDoor(main);
                        frmMain.AddNodeForms(onlyObj);
                    }
                }
            }
            return onlyObj;
        }

        private frmDoor(INMain main) : base(main)
        {
            InitializeComponent();
        }
        #endregion

        List<WeekTimeGroupDto> ListWeekTimeGroupDto = new List<WeekTimeGroupDto>();
        List<WeekTimeGroupDto> ListAutoLockedDto = new List<WeekTimeGroupDto>();
        WeekTimeGroup WeekTimeGroupPushButtonDto = new WeekTimeGroup(8);
        WeekTimeGroup WeekTimeGroupSensorAlarmDto = new WeekTimeGroup(8);
        WeekTimeGroup WeekTimeGroupWorkSettingDto = new WeekTimeGroup(8);
        List<List<decimal>> listGroupA = new List<List<decimal>>();
        List<List<decimal>> listGroupB = new List<List<decimal>>();
        List<MultiCard_GroupFix> listFix = new List<MultiCard_GroupFix>();

        private void ForCheckBoxDoorNum(Action<int> action)
        {
            for (int i = 1; i <= 4; i++)
            {
                var check = (tableLayoutPanel37.Controls.Find($"cBoxDoor{i}", true).FirstOrDefault() as CheckBox);
                if (check.Checked)
                {
                    action(i);
                }
            }
        }
        private void frmDoor_Load(object sender, EventArgs e)
        {
            LoadUILanguage();
            cbxReleaseTime.SelectedIndex = 0;


            InitGridReaderWork();

            #region 读卡器字节数默认选项
            cbxDoor1ReaderOption.SelectedIndex = 2;
            cbxDoor2ReaderOption.SelectedIndex = 2;
            cbxDoor3ReaderOption.SelectedIndex = 2;
            cbxDoor4ReaderOption.SelectedIndex = 2;
            #endregion

            #region 继电器参数默认选项
            cbxDoor1RelayOption.SelectedIndex = 0;
            cbxDoor2RelayOption.SelectedIndex = 0;
            cbxDoor3RelayOption.SelectedIndex = 0;
            cbxDoor4RelayOption.SelectedIndex = 0;
            #endregion

            #region 门工作方式_星期
            cbxWeek.SelectedIndex = 0;
            #endregion

            #region 重复读卡间隔_检测模式
            cbxDetectionMode.SelectedIndex = 0;

            #endregion

            WeekTimeGroupPushButtonDto.InitTimeGroup();
            cmbPushButtonWeekday.SelectedIndex = 0;

            WeekTimeGroupSensorAlarmDto.InitTimeGroup();

            #region
            string[] tgAnyCard = new string[64];
            for (int i = 1; i <= 64; i++)
            {
                tgAnyCard[i - 1] = i.ToString();
            }
            cmbAnyCardTimeGroup.Items.AddRange(tgAnyCard);
            cmbAnyCardTimeGroup.SelectedIndex = 0;
            #endregion

            #region 区域互锁
            string[] InterLockNum = new string[63];
            for (int i = 1; i < 64; i++)
            {
                InterLockNum[i - 1] = i.ToString();
            }
            cmbNum.Items.AddRange(InterLockNum);
            cmbNum.SelectedIndex = 0;
            #endregion

            cmbManyCardOpenMode.SelectedIndex = 0;
            cmbAntiPassback.SelectedIndex = 0;

            cmbGroupNum.Items.Clear();
            cmbGroupNum.Items.AddRange(new string[] { "1", "2", "3", "4", "5" });
            cmbGroupType.SelectedIndex = 0;
            //int[] ilist = new int[5];
            //for (int i = 1; i < 6; i++)
            //{
            //    cmbGroupNum.Items.Add(i);
            //}

            cmbGroupNum.SelectedIndex = 0;
            InitCardDataList();

        }


        public override void LoadUILanguage()
        {
            base.LoadUILanguage();
            // GetLanguage(label22);
            var door1 = GetLanguage("cBoxDoor1");
            var door2 = GetLanguage("cBoxDoor2");
            var door3 = GetLanguage("cBoxDoor3");
            var door4 = GetLanguage("cBoxDoor4");
            cBoxDoor1.Text = door1;
            cBoxDoor2.Text = door2;
            cBoxDoor3.Text = door3;
            cBoxDoor4.Text = door4;
            label24.Text = door1 + ":";
            label5.Text = door2 + ":";
            label12.Text = door3 + ":";
            label11.Text = door4 + ":";

            label16.Text = door1 + ":";
            label15.Text = door2 + ":";
            label14.Text = door3 + ":";
            label13.Text = door4 + ":";
            GetLanguage(tabPage1);
            GetLanguage(groupBox5);
            GetLanguage(btnReadReaderOption);
            GetLanguage(btnWriteReaderOption);
            GetLanguage(groupBox6);
            GetLanguage(btnReadRelayOption);
            GetLanguage(btnWriteRelayOption);
            GetLanguage(groupBox7);
            GetLanguage(btnOpenDoor);
            GetLanguage(btnCloseDoor);
            GetLanguage(btnHoldOpenDoor);
            GetLanguage(btnOpenDoor_CheckNum);
            GetLanguage(groupBox8);
            GetLanguage(btnLockDoor);
            GetLanguage(btnUnLockDoor);
            GetLanguage(groupBox11);
            GetLanguage(label38);
            GetLanguage(label39);
            GetLanguage(btnReadRelayReleaseTime);
            GetLanguage(btnWriteRelayReleaseTime);
            GetLanguage(groupBox16);
            GetLanguage(dataGridView1);
            GetLanguage(btnReadDoorWorkSetting);
            GetLanguage(btnWriteDoorWorkSetting);
            GetLanguage(groupBox9);
            GetLanguage(label57);
            GetLanguage(rBtnNoDoorWorkSetting);
            GetLanguage(rBtnDoorWorkSetting);
            GetLanguage(label17);
            GetLanguage(rBtnOpenDoorWay1);
            GetLanguage(rBtnOpenDoorWay2);
            GetLanguage(rBtnOpenDoorWay3);
            GetLanguage(rBtnOpenDoorWay4);
            GetLanguage(label18);
            GetLanguage(rBtnDoorTriggerMode1);
            GetLanguage(rBtnDoorTriggerMode2);
            GetLanguage(rBtnDoorTriggerMode3);
            GetLanguage(label19);
            GetLanguage(label20);
            GetLanguage(label21);
            GetLanguage(label29);
            GetLanguage(label28);
            GetLanguage(label33);
            GetLanguage(label32);
            GetLanguage(label37);
            GetLanguage(label36);
            GetLanguage(label25);
            GetLanguage(label23);
            GetLanguage(label27);
            GetLanguage(label26);
            GetLanguage(label31);
            GetLanguage(label30);
            GetLanguage(label35);
            GetLanguage(label34);
            GetLanguage(btnReadWorkSetting);
            GetLanguage(btnWriteWorkSetting);
            GetLanguage(groupBox10);
            GetLanguage(dataGridView2);
            GetLanguage(rBtnNoAutoLockedSetting);
            GetLanguage(rBtnAutoLockedSetting);
            GetLanguage(btnReadAutoLockedSetting);
            GetLanguage(btnWriteAutoLockedSetting);

            GetLanguage(tabPage3);
            GetLanguage(groupBox12);
            GetLanguage(rBtnNoReaderInterval);
            GetLanguage(rBtnReaderInterval);
            GetLanguage(label41);
            GetLanguage(label40);
            GetLanguage(groupBox13);
            GetLanguage(rBtnNotAnti);
            GetLanguage(rBtnAnti);
            GetLanguage(label42);
            GetLanguage(rBtnCheckInOut1);
            GetLanguage(rBtnCheckInOut2);
            GetLanguage(groupBox14);
            GetLanguage(cbReadPushButton);
            GetLanguage(cbNormallyOpen);
            GetLanguage(label62);
            GetLanguage(groupBox15);
            GetLanguage(cbAnyCardUse);
            GetLanguage(cbAnyCardAuto);
            GetLanguage(label44);
            GetLanguage(label63);
            GetLanguage(groupBox18);
            GetLanguage(cbInOutSideReadOpenSettingUse);
            GetLanguage(groupBox17);
            GetLanguage(cbVoiceBroadcastSettingUse);
            GetLanguage(groupBox19);
            GetLanguage(cbManageKeyboardSettingUse);
            GetLanguage(label64);
            GetLanguage(groupBox20);
            GetLanguage(label65);
            GetLanguage(label66);
            GetLanguage(lbSN);
            GetLanguage(lbIP);
            GetLanguage(lbPort);
            GetLanguage(groupBox21);
            GetLanguage(label70);
            GetLanguage(lbAreaType2);
            GetLanguage(lbAreaCode);
            GetLanguage(lbNum2);
            GetLanguage(lbIP2);
            GetLanguage(lbPort2);
            GetLanguage(tabPage4);
            GetLanguage(groupBox22);
            GetLanguage(label67);
            GetLanguage(label69);
            GetLanguage(label68);
            GetLanguage(label71);
            GetLanguage(label72);
            GetLanguage(lbgrouptype);
            GetLanguage(lbgroupnum);
            GetLanguage(cbConvertHex);
            GetLanguage(btnDeleteGroup);
            GetLanguage(btnAutoFill);
            GetLanguage(groupBox23);
            GetLanguage(cbReaderAlarmUse);
            GetLanguage(groupBox24);
            GetLanguage(label73);
            GetLanguage(cbInDoorUse);
            GetLanguage(label75);
            GetLanguage(label77);
            GetLanguage(label79);
            GetLanguage(label74);
            GetLanguage(cbOutDoorUse);
            GetLanguage(label76);
            GetLanguage(label78);
            GetLanguage(label80);
            GetLanguage(dataGridView5);
            GetLanguage(label61);
            GetLanguage(label60);
            GetLanguage(label56);
            GetLanguage(label55);
            GetLanguage(label52);
            GetLanguage(label51);
            GetLanguage(label48);
            GetLanguage(label47);
            GetLanguage(label59);
            GetLanguage(label58);
            GetLanguage(label54);
            GetLanguage(label53);
            GetLanguage(label50);
            GetLanguage(label49);
            GetLanguage(label46);
            GetLanguage(label45);

            var readBtn = GetLanguage("btnReadRelayOption");
            var write = GetLanguage("btnWriteRelayOption");

            btnReadReaderInterval.Text = readBtn;
            btnReadAntiPassback.Text = readBtn;
            btnReadPushButton.Text = readBtn;
            btnReadInOutSideReadOpenSetting.Text = readBtn;
            btnReadVoiceBroadcastSetting.Text = readBtn;
            btnReadAnyCard.Text = readBtn;
            btnReadManageKeyboardSetting.Text = readBtn;
            btnReadAreaAntiPassback.Text = readBtn;
            btnReadInterLockSetting.Text = readBtn;

            btnReadManyCardOpenMode.Text = readBtn;
            btnReadReaderAlarm.Text = readBtn;
            btnReadReadCardAndTakePictures.Text = readBtn;



            btnWriteReadCardAndTakePictures.Text = write;
            btnWriteReaderAlarm.Text = write;
            btnWriteManyCardOpenMode.Text = write;



            btnWriteInterLockSetting.Text = write;
            btnWriteAreaAntiPassback.Text = write;
            btnWriteManageKeyboardSetting.Text = write;
            btnWriteAnyCard.Text = write;
            btnWriteWriteVoiceBroadcastSetting.Text = write;
            btnWriteInOutSideReadOpenSetting.Text = write;
            btnWritePushButton.Text = write;
            btnWriteAntiPassback.Text = write;
            btnWriteReaderInterval.Text = write;


            string[] relayOption = new string[] { "COM & NC", "COM & NO" };
            var doorRelayOption = GetLanguage("DoorRelayOption");
            cbxDoor1RelayOption.Items.Clear();
            cbxDoor1RelayOption.Items.AddRange(relayOption);
            cbxDoor1RelayOption.Items.Add(doorRelayOption);

            cbxDoor2RelayOption.Items.Clear();
            cbxDoor2RelayOption.Items.AddRange(relayOption);
            cbxDoor2RelayOption.Items.Add(doorRelayOption);

            cbxDoor3RelayOption.Items.Clear();
            cbxDoor3RelayOption.Items.AddRange(relayOption);
            cbxDoor3RelayOption.Items.Add(doorRelayOption);

            cbxDoor4RelayOption.Items.Clear();
            cbxDoor4RelayOption.Items.AddRange(relayOption);
            cbxDoor4RelayOption.Items.Add(doorRelayOption);

            var detectionMode = GetLanguage("cbxDetectionMode").Split(',');
            cbxDetectionMode.Items.Clear();
            cbxDetectionMode.Items.AddRange(detectionMode);
            string[] str = GetLanguage("Door1ReaderOption").Split(',');
            cbxDoor1ReaderOption.Items.Clear();
            cbxDoor1ReaderOption.Items.AddRange(str);
            cbxDoor1ReaderOption.SelectedIndex = 0;

            var areaType = GetLanguage("cmbAreaType").Split(',');
            cmbAreaType.Items.Clear();
            cmbAreaType.Items.AddRange(areaType);
            cmbAreaType.SelectedIndex = 0;


            cmbInterLockSettingAreaType.Items.Clear();
            cmbInterLockSettingAreaType.Items.AddRange(areaType);
            cmbInterLockSettingAreaType.SelectedIndex = 0;

            cbxDoor2ReaderOption.Items.Clear();
            cbxDoor2ReaderOption.Items.AddRange(str);
            cbxDoor2ReaderOption.SelectedIndex = 0;

            cbxDoor3ReaderOption.Items.Clear();
            cbxDoor3ReaderOption.Items.AddRange(str);
            cbxDoor3ReaderOption.SelectedIndex = 0;

            cbxDoor4ReaderOption.Items.Clear();
            cbxDoor4ReaderOption.Items.AddRange(str);
            cbxDoor4ReaderOption.SelectedIndex = 0;

            cmbInterval.Items.Clear();
            string[] time = new string[256];
            string disable = GetLanguage("Msg2");
            string seconds = GetLanguage("Msg1");
            for (int i = 0; i < 256; i++)
            {
                time[i] = i.ToString() + seconds;
                if (time[0] == ("0" + seconds))
                    time[0] = disable;
            }
            cmbInterval.Items.AddRange(time);
            cmbInterval.Items.Add("65535" + seconds);
            cmbInterval.SelectedIndex = cmbInterval.Items.Count - 1;
            string temp1 = GetLanguage("Msg3");
            string temp2 = GetLanguage("Msg4");
            string temp3 = GetLanguage("Msg5");
            string use = GetLanguage("Msg6");
            cmbVerifyType.Items.Clear();
            if (!CheckProtocolTypeIs89H())
            {
                cmbVerifyType.Items.AddRange(new string[] { disable, temp1 });
            }
            else
            {
                cmbVerifyType.Items.AddRange(new string[] { disable, temp2, temp1, temp3 });
            }
            cmbVerifyType.SelectedIndex = 0;


            cmbManyCardOpenMode.Items.Clear();
            cmbManyCardOpenMode.Items.AddRange(GetLanguage("cmbManyCardOpenMode").Split(','));
            cmbManyCardOpenMode.SelectedIndex = 0;

            cmbAntiPassback.Items.Clear();
            cmbAntiPassback.Items.AddRange(GetLanguage("cmbAntiPassback").Split(','));
            cmbAntiPassback.SelectedIndex = 0;

            cmbGroupType.Items.Clear();
            cmbGroupType.Items.AddRange(GetLanguage("cmbGroupType").Split(','));
            cmbGroupType.SelectedIndex = 0;
            var week = GetLanguage("WeekOption").Split(',');
            cmbPushButtonWeekday.Items.Clear();
            cmbPushButtonWeekday.Items.AddRange(week);
            cmbPushButtonWeekday.SelectedIndex = 0;

            Cmb_InOutType.Items.Clear();
            Cmb_InOutType.Items.AddRange(GetLanguage("Cmb_InOutType").Split(','));
            Cmb_InOutType.SelectedIndex = 0;

            SetControlsFont(this.Controls, GetLanguageFont());
        }
        private void InitGridReaderWork()
        {
            Random r = new Random();
            for (int i = 0; i < 7; i++)
            {
                WeekTimeGroupDto dto = new WeekTimeGroupDto();
                dto.WeekDay = GetWeekStr(i);
                dto.Ex = "-";
                dto.IsEx = "true";
                ListWeekTimeGroupDto.Add(dto);
                ListAutoLockedDto.Add(dto);
                for (int j = 0; j < 8; j++)
                {
                    dto = new WeekTimeGroupDto();
                    dto.WeekDay = (j + 1).ToString();

                    dto.id0 =
                    dto.id1 =
                    dto.id2 =
                    dto.id3 = j == 0;
                    dto.WeekDayIndex = i;
                    if (j == 0)
                    {
                        dto.StartTime = "00:00";
                        dto.EndTime = "23:59";
                    }
                    else
                    {
                        dto.StartTime = "00:00";
                        dto.EndTime = "00:00";
                    }
                    ListWeekTimeGroupDto.Add(dto);
                    ListAutoLockedDto.Add(dto);
                }
            }
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = new BindingList<WeekTimeGroupDto>(ListWeekTimeGroupDto);

            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.DataSource = new BindingList<WeekTimeGroupDto>(ListAutoLockedDto);

        }




        #region 读卡器参数读写
        public bool CheckProtocolTypeIs89H()
        {
            return mMainForm.CheckProtocolTypeIs89H();
        }

        private void BtnReadReaderOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadReaderOption cmd = new ReadReaderOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReaderOption_Result result = cmde.Command.getResult() as ReaderOption_Result;
                StringBuilder sb = new StringBuilder();
                string[] str = GetLanguage("Door1ReaderOption").Split(',');
                Invoke(() =>
                {
                    int count = 2;
                    if (CheckProtocolTypeIs89H())
                    {
                        count = 4;
                    }
                    string sDoor = GetLanguage("Msg15");
                    for (int i = 0; i < 4; i++)
                    {
                        if (i + 1 > count)
                        {
                            break;
                        }
                        //门1读卡器字节数
                        if (i == 0)
                        {
                            cbxDoor1ReaderOption.SelectedIndex = result.Door[i] - 1;
                        }
                        //门2读卡器字节数
                        if (i == 1)
                        {
                            cbxDoor2ReaderOption.SelectedIndex = result.Door[i] - 1;
                        }
                        //门3读卡器字节数
                        if (i == 2)
                        {
                            cbxDoor3ReaderOption.SelectedIndex = result.Door[i] - 1;
                        }
                        //门4读卡器字节数
                        if (i == 3)
                        {
                            cbxDoor4ReaderOption.SelectedIndex = result.Door[i] - 1;
                        }
                        sb.AppendLine(sDoor + (i + 1) + ":" + str[result.Door[i] - 1]);
                    }
                });
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }

        private void BtnWriteReaderOption_Click(object sender, EventArgs e)
        {


            byte[] Door = new byte[4];
            //门1读卡器字节数
            Door[0] = (byte)(cbxDoor1ReaderOption.SelectedIndex + 1);
            Door[1] = (byte)(cbxDoor2ReaderOption.SelectedIndex + 1);
            if (CheckProtocolTypeIs89H())
            {
                Door[2] = (byte)(cbxDoor3ReaderOption.SelectedIndex + 1);
                Door[3] = (byte)(cbxDoor4ReaderOption.SelectedIndex + 1);
            }
            else
            {
                Door[2] = 0;
                Door[3] = 0;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            if (CheckProtocolTypeIs89H())
            {
                ReaderOption_Parameter par = new ReaderOption_Parameter(Door);
                WriteReaderOption<ReaderOption_Parameter> cmd = new WriteReaderOption<ReaderOption_Parameter>(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            }
            else if (CheckProtocolTypeIs89H())
            {
                Door89H.Door.ReaderOption.ReaderOption_Parameter par = new Door89H.Door.ReaderOption.ReaderOption_Parameter(Door);
                WriteReaderOption<Door89H.Door.ReaderOption.ReaderOption_Parameter> cmd = new WriteReaderOption<Door89H.Door.ReaderOption.ReaderOption_Parameter>(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            }
        }
        #endregion

        #region 继电器参数读写
        private void BtnReadRelayOption_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadRelayOption cmd = new ReadRelayOption(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                RelayOption_Result result = cmde.Command.getResult() as RelayOption_Result;
                StringBuilder sb = new StringBuilder();
                string[] str = new string[3];
                str[0] = GetLanguage("Msg16");
                str[1] = GetLanguage("Msg17");
                str[2] = GetLanguage("Msg18");

                Invoke(() =>
                {
                    var door = GetLanguage("Msg15");
                    for (int i = 0; i < 4; i++)
                    {
                        //门1继电器参数
                        if (i == 0)
                        {
                            GetRelayLog(sb, door, str, i, result.Relay, cbxDoor1RelayOption);
                        }
                        //门2继电器参数
                        if (i == 1)
                        {
                            GetRelayLog(sb, door, str, i, result.Relay, cbxDoor2RelayOption);
                        }
                        //门3继电器参数
                        if (i == 2)
                        {
                            GetRelayLog(sb, door, str, i, result.Relay, cbxDoor3RelayOption);
                        }
                        //门4继电器参数
                        if (i == 3)
                        {
                            GetRelayLog(sb, door, str, i, result.Relay, cbxDoor4RelayOption);
                        }
                    }
                });
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }
        /// <summary>
        /// 继电器参数打印
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="door"></param>
        /// <param name="str"></param>
        /// <param name="i"></param>
        /// <param name="Relay"></param>
        /// <param name="comboBox"></param>
        private void GetRelayLog(StringBuilder sb, string door, string[] str, int i, byte[] Relay, ComboBox comboBox)
        {
            var index = Relay[i] - 1;
            comboBox.SelectedIndex = index;
            sb.AppendLine(door + (i + 1) + "," + str[index]);
        }

        private void BtnWriteRelayOption_Click(object sender, EventArgs e)
        {
            byte[] Relay = new byte[4];
            Relay[0] = Convert.ToByte(cbxDoor1RelayOption.SelectedIndex + 1); //门1继电器参数
            Relay[1] = Convert.ToByte(cbxDoor2RelayOption.SelectedIndex + 1); //门2继电器参数
            Relay[2] = Convert.ToByte(cbxDoor3RelayOption.SelectedIndex + 1); //门3继电器参数
            Relay[3] = Convert.ToByte(cbxDoor4RelayOption.SelectedIndex + 1); //门4继电器参数

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteRelayOption cmd = new WriteRelayOption(cmdDtl, new RelayOption_Parameter(Relay));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 远程开关门
        private void BtnOpenDoor_Click(object sender, EventArgs e)
        {
            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            OpenDoor cmd = new OpenDoor(cmdDtl, new Remote_Parameter(Door));
            mMainForm.AddCommand(cmd);
        }

        private void BtnCloseDoor_Click(object sender, EventArgs e)
        {
            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseDoor cmd = new CloseDoor(cmdDtl, new Remote_Parameter(Door));
            mMainForm.AddCommand(cmd);
        }

        private void BtnHoldOpenDoor_Click(object sender, EventArgs e)
        {
            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            HoldDoor cmd = new HoldDoor(cmdDtl, new Remote_Parameter(Door));
            mMainForm.AddCommand(cmd);
        }

        private void BtnOpenDoor_CheckNum_Click(object sender, EventArgs e)
        {
            byte CheckNum;
            CheckNum = Convert.ToByte(StringUtility.GetRandomNum(1, 254));

            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            OpenDoor_CheckNum cmd = new OpenDoor_CheckNum(cmdDtl, new Remote_CheckNum_Parameter(Door, CheckNum));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 门的锁定与解除
        private void BtnLockDoor_Click(object sender, EventArgs e)
        {
            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            LockDoor cmd = new LockDoor(cmdDtl, new Remote_Parameter(Door));
            mMainForm.AddCommand(cmd);
        }

        private void BtnUnLockDoor_Click(object sender, EventArgs e)
        {
            DoorDetail<bool> Door = new DoorDetail<bool>();
            Door.SetDoor(1, cBoxDoor1.Checked);
            Door.SetDoor(2, cBoxDoor2.Checked);
            Door.SetDoor(3, cBoxDoor3.Checked);
            Door.SetDoor(4, cBoxDoor4.Checked);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            UnlockDoor cmd = new UnlockDoor(cmdDtl, new Remote_Parameter(Door));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 读卡认证方式的读写
        private void BtnReadDoorWorkSetting_Click(object sender, EventArgs e)
        {

            ForCheckBoxDoorNum((doorNum) =>
            {
                StringBuilder sb = new StringBuilder();
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                ReadReaderWorkSetting cmd = new ReadReaderWorkSetting(cmdDtl, new DoorPort_Parameter(doorNum));
                mMainForm.AddCommand(cmd);

                //处理返回值
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {

                    ReaderWorkSetting_Result result = cmde.Command.getResult() as ReaderWorkSetting_Result;
                    ListWeekTimeGroupDto.Clear();
                    StringBuilder log = new StringBuilder();
                    var cols = GetLanguage("dataGridView1_Cols").Split(',');
                    for (int i = 0; i < 7; i++)
                    {
                        log.Clear();
                        var weekdto = GetTimeGroupDto(i, 0, false, null);
                        ListWeekTimeGroupDto.Add(weekdto);
                        log.AppendLine($"{GetLanguage("label22")}:{doorNum}," + weekdto.WeekDay);
                        for (int j = 0; j < 8; j++)
                        {
                            var tz = result.weekTimeGroup_ReaderWork.GetItem(i).GetItem(j) as TimeSegment_ReaderWork;
                            var dayDto = GetTimeGroupDto(i, j, true, tz);
                            log.AppendLine(ShowWeekTimeGroup(dayDto, cols));
                            ListWeekTimeGroupDto.Add(dayDto);
                        }
                        mMainForm.AddCmdLog(cmde, log.ToString());
                    }
                    Invoke(() =>
                    {
                        dataGridView1.DataSource = new BindingList<WeekTimeGroupDto>(ListWeekTimeGroupDto);
                    });
                };
            });

        }
        private WeekTimeGroupDto GetTimeGroupDto(int i, int j, bool isDay, TimeSegment_ReaderWork tz)
        {
            if (isDay && tz != null)
            {
                var bitSet = new BitArray(new byte[] { tz.GetCheckWay() });
                return new WeekTimeGroupDto
                {
                    WeekDay = (j + 1).ToString(),
                    WeekDayIndex = i,
                    StartTime = tz.GetBeginTime().ToString("HH:mm"),
                    EndTime = tz.GetEndTime().ToString("HH:mm"),
                    id0 = bitSet[0],
                    id1 = bitSet[1],
                    id2 = bitSet[2],
                    id3 = bitSet[3]
                };
            }
            else
            {
                return new WeekTimeGroupDto
                {
                    WeekDay = GetWeekStr(i),
                    Ex = "-",
                    IsEx = "true"
                };
            }
        }
        private string ShowWeekTimeGroup(WeekTimeGroupDto dayDto, string[] cols)
        {
            StringBuilder log = new StringBuilder();
            log.Append($"{GetLanguage("Msg37")}:{dayDto.WeekDay}:{dayDto.StartTime}-{dayDto.EndTime};");
            log.Append($"{GetLanguage("groupBox16")}：{ShowCheck(dayDto.id0, cols[5])}{ShowCheck(dayDto.id1, cols[6])}{ShowCheck(dayDto.id2, cols[7])}{ShowCheck(dayDto.id3, cols[8])}");
            return log.ToString();
        }
        private string ShowCheck(bool isShow, string msg)
        {
            return isShow ? msg + ";" : string.Empty;
        }

        /// <summary>
        /// 获得数值代表的星期
        /// </summary>
        /// <param name="index">数值（0-6，0代表星期一...6代表星期日）</param>
        /// <returns></returns>
        private string GetWeekStr(int index)
        {
            string weekStr = string.Empty;
            if (index == 0)
            {
                return GetLanguage("Msg20");
            }
            else if (index == 1)
            {
                return GetLanguage("Msg21");
            }
            else if (index == 2)
            {
                return GetLanguage("Msg22");
            }
            else if (index == 3)
            {
                return GetLanguage("Msg23");
            }
            else if (index == 4)
            {
                return GetLanguage("Msg24");
            }
            else if (index == 5)
            {
                return GetLanguage("Msg25");
            }
            else if (index == 6)
            {
                return GetLanguage("Msg26");
            }
            return weekStr;
        }

        /// <summary>
        /// 设置读卡认证方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteDoorWorkSetting_Click(object sender, EventArgs e)
        {
            ForCheckBoxDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                WeekTimeGroup_ReaderWork tg = new WeekTimeGroup_ReaderWork(8);
                ConvertDtoToModel(tg);
                WriteReaderWorkSetting_Parameter par = new WriteReaderWorkSetting_Parameter((byte)(doorNum), tg);
                WriteReaderWorkSetting write = new WriteReaderWorkSetting(cmdDtl, par);
                mMainForm.AddCommand(write);
            });

        }

        /// <summary>
        /// GridView数据 转换成 WeekTimeGroup_ReaderWork
        /// </summary>
        /// <param name="tg"></param>
        private void ConvertDtoToModel(WeekTimeGroup_ReaderWork tg)
        {
            for (int i = 0; i < 7; i++)
            {
                var day = tg.GetItem(i);
                for (int j = 0; j < 8; j++)
                {
                    var dto = ListWeekTimeGroupDto.FirstOrDefault(t => t.WeekDay == (j + 1).ToString() && t.WeekDayIndex == i);
                    //DateTime nw = DateTime.Now;
                    var tz = day.GetItem(j) as TimeSegment_ReaderWork;
                    string[] tsStart = dto.StartTime.Split(':');
                    string[] tsEnd = dto.EndTime.Split(':');
                    tz.SetBeginTime(int.Parse(tsStart[0]), int.Parse(tsStart[1]));
                    tz.SetEndTime(int.Parse(tsEnd[0]), int.Parse(tsEnd[1]));
                    string strDoor1 = (dto.id3 ? "1" : "0") + (dto.id2 ? "1" : "0") + (dto.id1 ? "1" : "0") + (dto.id0 ? "1" : "0");
                    byte checkWay = Convert.ToByte(strDoor1, 2);

                    tz.SetCheckWay(checkWay);
                }
            }

        }

        #endregion

        #region 门工作方式

        private void BtnReadWorkSetting_Click(object sender, EventArgs e)
        {
            var OpenDoorWayKeys = new string[] { string.Empty, GetLanguage("Msg28"), GetLanguage("Msg29"), GetLanguage("Msg30"), GetLanguage("Msg31") };
            var DoorTriggerModeKeys = new string[] { string.Empty, GetLanguage("Msg33"), GetLanguage("Msg34"), GetLanguage("Msg35") };
            ForCheckBoxDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                ReadDoorWorkSetting cmd = new ReadDoorWorkSetting(cmdDtl, new DoorPort_Parameter(doorNum));
                mMainForm.AddCommand(cmd);
                //处理返回值
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    DoorWorkSetting_Result result = cmde.Command.getResult() as DoorWorkSetting_Result;
                    //开门方式是首卡或者常开状态时
                    if (result.OpenDoorWay == 3 || result.OpenDoorWay == 4)
                    {
                        for (int i = 0; i < 7; i++)
                        {
                            mMainForm.AddCmdLog(cmde, ShowDoorDayTimeGroup(GetWeekStr(i), result.weekTimeGroup.GetItem(i)));
                        }
                    }
                    mMainForm.AddCmdLog(cmde, GetDoorWorkSettingLog(result, OpenDoorWayKeys, DoorTriggerModeKeys));
                    SetDoorWorkSetting(result);
                };
            });


        }
        /// <summary>
        /// 获取打印日志
        /// </summary>
        /// <param name="result"></param>
        /// <param name="OpenDoorWayKeys"></param>
        /// <param name="DoorTriggerModeKeys"></param>
        /// <returns></returns>
        private string GetDoorWorkSettingLog(DoorWorkSetting_Result result, string[] OpenDoorWayKeys, string[] DoorTriggerModeKeys)
        {
            StringBuilder sb = new StringBuilder();
            if (result.Use == 0)
            {
                sb.AppendLine(GetLanguage("Msg15") + result.Door + "：" + GetLanguage("Msg27"));
                return sb.ToString();
            }
            //开门方式
            sb.AppendLine(GetLanguage("Msg15") + result.Door + $"：{GetLanguage("Msg32")}：" + OpenDoorWayKeys[result.OpenDoorWay]);
            //常开触发模式
            var DoorTriggerModeStr = DoorTriggerModeKeys[result.DoorTriggerMode];
            if (result.OpenDoorWay == 4)
            {
                sb.AppendLine($"；{GetLanguage("Msg36")}：" + DoorTriggerModeStr);
            }
            return sb.ToString();
        }

        private string ShowDoorDayTimeGroup(string weekDay, DayTimeGroup dayTimeGroup)
        {
            var sb = new StringBuilder();
            sb.AppendLine(weekDay);
            for (int i = 0; i < 8; i++)
            {
                sb.Append(StringUtility.TimeHourAndMinuteStr(dayTimeGroup.GetItem(i).GetBeginTime(), dayTimeGroup.GetItem(i).GetEndTime())).Append("；");
                if (i == 3)
                    sb.AppendLine();

            }
            return sb.ToString();
        }
        /// <summary>
        /// 设置控件参数
        /// </summary>
        /// <param name="result"></param>
        private void SetDoorWorkSetting(DoorWorkSetting_Result result)
        {
            Invoke(() =>
            {
                rBtnDoorWorkSetting.Checked = !(rBtnNoDoorWorkSetting.Checked = result.Use == 0);
                if (rBtnNoDoorWorkSetting.Checked)
                {
                    return;
                }
                //开门方式
                rBtnOpenDoorWay1.Checked = result.OpenDoorWay == 1;
                rBtnOpenDoorWay2.Checked = result.OpenDoorWay == 2;
                rBtnOpenDoorWay3.Checked = result.OpenDoorWay == 3;
                rBtnOpenDoorWay4.Checked = result.OpenDoorWay == 4;
                //常开触发模式
                rBtnDoorTriggerMode1.Checked = result.DoorTriggerMode == 1;
                rBtnDoorTriggerMode2.Checked = result.DoorTriggerMode == 2;
                rBtnDoorTriggerMode3.Checked = result.DoorTriggerMode == 3;
                //开门方式是首卡或者常开状态时
                if (result.OpenDoorWay != 3 && result.OpenDoorWay != 4)
                {
                    return;
                }
                WeekTimeGroupWorkSettingDto = result.weekTimeGroup;
                SetAllTimePicker(tableLayoutPanel36, "beginTimePicker", "endTimePicker", WeekTimeGroupWorkSettingDto.GetItem(cbxWeek.SelectedIndex));
            });
        }

        private void BtnWriteWorkSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            var use = (byte)(rBtnDoorWorkSetting.Checked ? 1 : 0); //功能是否启用
            var openDoorWay = GetOpenDoorWay(); //开门方式
            var doorTriggerMode = GetDoorTriggerMode(); //门常开触发模式
            var retainValue = (byte)0; //保留值          
            ForCheckBoxDoorNum((doorNum) =>
            {
                var par = new WriteDoorWorkSetting_Parameter((byte)(doorNum),
                    use,
                    openDoorWay,
                    doorTriggerMode,
                    retainValue,
                    WeekTimeGroupWorkSettingDto);
                var write = new WriteDoorWorkSetting(cmdDtl, par);
                mMainForm.AddCommand(write);
            });
        }
        /// <summary>
        /// 获取开门方式
        /// </summary>
        /// <returns></returns>
        private byte GetOpenDoorWay()
        {
            return (byte)(rBtnOpenDoorWay1.Checked ? 1 :
                rBtnOpenDoorWay2.Checked ? 2 :
                rBtnOpenDoorWay3.Checked ? 3 :
                rBtnOpenDoorWay4.Checked ? 4 :
                1); //开门方式
        }
        /// <summary>
        /// 获取门常开触发模式
        /// </summary>
        /// <returns></returns>
        private byte GetDoorTriggerMode()
        {
            return (byte)(rBtnDoorTriggerMode1.Checked ? 1 :
                rBtnDoorTriggerMode2.Checked ? 2 :
                rBtnDoorTriggerMode3.Checked ? 3 :
                1);
        }

        private void CbxWeek_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (WeekTimeGroupWorkSettingDto != null)
            {
                var day = WeekTimeGroupWorkSettingDto.GetItem(cbxWeek.SelectedIndex);
                SetAllTimePicker(tableLayoutPanel36, "beginTimePicker", "endTimePicker", day);
            }
        }

        private void BeginTimePicker_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupWorkSettingDto, cbxWeek.SelectedIndex, int.Parse(dtp.Name.Substring(15)) - 1, 1, dtp.Value);
        }

        private void EndTimePicker_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupWorkSettingDto, cbxWeek.SelectedIndex, int.Parse(dtp.Name.Substring(13)) - 1, 2, dtp.Value);
        }

        /// <summary>
        /// 选择不启用高级功能按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnNoDoorWorkSetting_CheckedChanged(object sender, EventArgs e)
        {
            //OpenDoorWayPanel.Visible = false;
            // DoorTriggerModePanel.Visible = false;
            DoorOpenTimePanel.Visible = false;
        }

        /// <summary>
        /// 选择启用高级功能按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnDoorWorkSetting_CheckedChanged(object sender, EventArgs e)
        {
            //  OpenDoorWayPanel.Visible = true;
        }
        /// <summary>
        /// 选择开门方式是普通按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnOpenDoorWay1_CheckedChanged(object sender, EventArgs e)
        {
            DoorOpenTimePanel.Visible = false;
            // DoorTriggerModePanel.Visible = false;
        }
        /// <summary>
        /// 选择开门方式是多卡按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnOpenDoorWay2_CheckedChanged(object sender, EventArgs e)
        {
            DoorOpenTimePanel.Visible = false;
            //  DoorTriggerModePanel.Visible = false;
        }
        /// <summary>
        /// 选择开门方式是首卡按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnOpenDoorWay3_CheckedChanged(object sender, EventArgs e)
        {
            DoorOpenTimePanel.Visible = true;
            //  DoorTriggerModePanel.Visible = false;
        }

        /// <summary>
        /// 选择开门方式是常开按钮时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtnOpenDoorWay4_CheckedChanged(object sender, EventArgs e)
        {
            //  DoorTriggerModePanel.Visible = true;
            DoorOpenTimePanel.Visible = true;
        }


        #endregion

        #region 定时锁定门参数读写
        private void ConvertDtoToModel(WeekTimeGroup tg)
        {
            for (int i = 0; i < 7; i++)
            {
                var day = tg.GetItem(i);
                for (int j = 0; j < 8; j++)
                {
                    var dto = ListAutoLockedDto.FirstOrDefault(t => t.WeekDay == (j + 1).ToString() && t.WeekDayIndex == i);
                    //DateTime nw = DateTime.Now;
                    var tz = day.GetItem(j) as TimeSegment;
                    string[] tsStart = dto.StartTime.Split(':');
                    string[] tsEnd = dto.EndTime.Split(':');
                    tz.SetBeginTime(int.Parse(tsStart[0]), int.Parse(tsStart[1]));
                    tz.SetEndTime(int.Parse(tsEnd[0]), int.Parse(tsEnd[1]));
                }
            }

        }
        private void BtnReadAutoLockedSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                ReadAutoLockedSetting cmd = new ReadAutoLockedSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            StringBuilder log = new StringBuilder();
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                AutoLockedSetting_Result result = cmde.Command.getResult() as AutoLockedSetting_Result;
                ListAutoLockedDto.Clear();
                for (int i = 0; i < 7; i++)
                {
                    WeekTimeGroupDto dto = new WeekTimeGroupDto
                    {
                        WeekDay = GetWeekStr(i),
                        Ex = "-",
                        IsEx = "true"
                    };
                    ListAutoLockedDto.Add(dto);
                    log.AppendLine($"{GetLanguage("label22")}:{result.Door}," + dto.WeekDay);
                    for (int j = 0; j < 8; j++)
                    {
                        var tz = result.weekTimeGroup.GetItem(i).GetItem(j) as TimeSegment;
                        dto = new WeekTimeGroupDto
                        {
                            WeekDay = (j + 1).ToString(),
                            WeekDayIndex = i,
                            StartTime = tz.GetBeginTime().ToString("HH:mm"),
                            EndTime = tz.GetEndTime().ToString("HH:mm")
                        };
                        ListAutoLockedDto.Add(dto);
                        log.Append(StringUtility.TimeHourAndMinuteStr(tz.GetBeginTime(), tz.GetEndTime())).Append("  ");
                        if (j == 3)
                            log.AppendLine();
                    }
                    if (result.Use == 1)
                        mMainForm.AddCmdLog(cmde, log.ToString());
                    log.Clear();
                }
                Invoke(() =>
                {
                    dataGridView2.DataSource = new BindingList<WeekTimeGroupDto>(ListAutoLockedDto);
                    rBtnNoAutoLockedSetting.Checked = result.Use == 0;
                    rBtnAutoLockedSetting.Checked = !rBtnNoAutoLockedSetting.Checked;
                });
                string useStr = result.Use == 0 ? GetLanguage("Msg38") : GetLanguage("Msg39");
                mMainForm.AddCmdLog(cmde, $"{GetLanguage("groupBox10")}:{useStr}");

            };
        }

        private void BtnWriteAutoLockedSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WeekTimeGroup tg = new WeekTimeGroup(8);
            ConvertDtoToModel(tg);
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                byte use = (byte)(rBtnAutoLockedSetting.Checked ? 1 : 0);
                AutoLockedSetting_Parameter par = new AutoLockedSetting_Parameter(door, use, tg);
                WriteAutoLockedSetting write = new WriteAutoLockedSetting(cmdDtl, par);
                mMainForm.AddCommand(write);
            });
        }
        #endregion

        #region 开锁时输出时长
        private void BtnReadRelayReleaseTime_Click(object sender, EventArgs e)
        {

            ForCheckBoxDoorNum((doorNum) =>
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                ReadRelayReleaseTime cmd = new ReadRelayReleaseTime(cmdDtl, new DoorPort_Parameter(doorNum));
                mMainForm.AddCommand(cmd);
                //处理返回值
                cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                {
                    StringBuilder sb = new StringBuilder();
                    RelayReleaseTime_Result result = cmde.Command.getResult() as RelayReleaseTime_Result;
                    string tip = string.Empty;
                    sb.Append(GetLanguage("Msg15") + result.Door + $",{GetLanguage("Msg43")}：");
                    var Msg1 = GetLanguage("Msg1");
                    if (result.ReleaseTime == 0)
                    {
                        tip = "0.5" + Msg1;
                    }
                    else
                    {
                        tip = result.ReleaseTime + Msg1;
                    }

                    Invoke(() =>
                    {
                        cbxReleaseTime.Text = tip.Replace(Msg1, "");
                    });
                    sb.AppendLine(tip);
                    mMainForm.AddCmdLog(cmde, sb.ToString());
                };
            });
        }

        private void BtnWriteRelayReleaseTime_Click(object sender, EventArgs e)
        {
            /*
            if (!cBoxDoor1.Checked && !cBoxDoor2.Checked && !cBoxDoor3.Checked && !cBoxDoor4.Checked)
            {
                MsgErr(GetLanguage("Msg19"));
                return;
            }
            */
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(cbxReleaseTime.Text.Trim(), reg))
            {
                if (cbxReleaseTime.Text != "0.5")
                {
                    MsgErr(GetLanguage("Msg44"));
                    return;
                }
            }
            if (Regex.IsMatch(cbxReleaseTime.Text.Trim(), reg))
            {
                if (Convert.ToUInt32(cbxReleaseTime.Text) < 0 || Convert.ToUInt32(cbxReleaseTime.Text) > 65535)
                {
                    MsgErr(GetLanguage("Msg44"));
                    return;
                }
            }

            byte door = (byte)(1);
            ushort releaseTime = 0;
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            if (cbxReleaseTime.Text != "0.5")
            {
                releaseTime = Convert.ToUInt16(cbxReleaseTime.Text);
            }
            WriteRelayReleaseTime_Parameter par = new WriteRelayReleaseTime_Parameter(door, releaseTime);
            WriteRelayReleaseTime write = new WriteRelayReleaseTime(cmdDtl, par);
            mMainForm.AddCommand(write);
            /*
            if (cBoxDoor1.Checked)
            {
                door = 1;
                WriteRelayReleaseTime_Parameter par = new WriteRelayReleaseTime_Parameter(door, releaseTime);
                WriteRelayReleaseTime write = new WriteRelayReleaseTime(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor2.Checked)
            {
                door = 2;
                WriteRelayReleaseTime_Parameter par = new WriteRelayReleaseTime_Parameter(door, releaseTime);
                WriteRelayReleaseTime write = new WriteRelayReleaseTime(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor3.Checked)
            {
                door = 3;
                WriteRelayReleaseTime_Parameter par = new WriteRelayReleaseTime_Parameter(door, releaseTime);
                WriteRelayReleaseTime write = new WriteRelayReleaseTime(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor4.Checked)
            {
                door = 4;
                WriteRelayReleaseTime_Parameter par = new WriteRelayReleaseTime_Parameter(door, releaseTime);
                WriteRelayReleaseTime write = new WriteRelayReleaseTime(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            */
        }
        #endregion

        #region 重复读卡间隔参数
        private void BtnReadReaderInterval_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            ReadReaderIntervalTime cmd0 = new ReadReaderIntervalTime(cmdDtl);
            mMainForm.AddCommand(cmd0);
            ForCheckBoxDoorNum((doorNum) =>
            {
                StringBuilder sb = new StringBuilder();
                string UseStr = string.Empty;
                string DetectionModeStr = string.Empty;
                byte door = (byte)doorNum;
                ReadReaderInterval cmd = new ReadReaderInterval(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
                //处理返回值
            });
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                if (cmde.Command.getResult() is ReadReaderIntervalTime_Result IntervalTimeResult)
                {
                    Invoke(() =>
                    {
                        if (IntervalTimeResult.IntervalTime == 65535)
                        {
                            cmbInterval.SelectedIndex = cmbInterval.Items.Count - 1;
                        }
                        else
                        {
                            cmbInterval.SelectedIndex = IntervalTimeResult.IntervalTime;
                        }
                        mMainForm.AddCmdLog(cmde, label41.Text + cmbInterval.Text);
                    });
                }
                if (cmde.Command.getResult() is ReaderInterval_Result result)
                {
                    Invoke(() =>
                    {
                        if (result.Use == 0)
                        {
                            rBtnNoReaderInterval.Checked = true;
                        }
                        cbxDetectionMode.SelectedIndex = result.DetectionMode - 1;
                    });
                    mMainForm.AddCmdLog(cmde, GetReaderIntervalLog(result));
                }

            };
        }

        private string GetReaderIntervalLog(ReaderInterval_Result result)
        {
            if (result.Use == 0)
            {
                return GetLanguage("Msg15") + result.Door + $":{Environment.NewLine}{GetLanguage("Msg48")}:" + GetLanguage("Msg38");
            }
            string DetectionModeStr = string.Empty;
            if (result.DetectionMode == 1)
            {
                DetectionModeStr = GetLanguage("Msg45");
            }
            else if (result.DetectionMode == 2)
            {
                DetectionModeStr = GetLanguage("Msg46");
            }
            else if (result.DetectionMode == 3)
            {
                DetectionModeStr = GetLanguage("Msg47");
            }
            return $"{GetLanguage("Msg15")}{result.Door}:{GetLanguage("Msg39")}{Environment.NewLine}{GetLanguage("Msg49")}:" + DetectionModeStr;
        }



        private void BtnWriteReaderInterval_Click(object sender, EventArgs e)
        {
            /*
            if (!cBoxDoor1.Checked && !cBoxDoor2.Checked && !cBoxDoor3.Checked && !cBoxDoor4.Checked)
            {
                MsgErr(GetLanguage("Msg19"));
                return;
            }
            */
            byte door = (byte)(1); //门
            byte use = 0; //功能是否启用
            byte detectionMode = 1; //检测模式
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            if (rBtnReaderInterval.Checked)
            {
                use = 1;
            }
            detectionMode = Convert.ToByte(cbxDetectionMode.SelectedIndex + 1);
            WriteReaderInterval_Parameter par = new WriteReaderInterval_Parameter(door, use, detectionMode);
            WriteReaderInterval write = new WriteReaderInterval(cmdDtl, par);
            mMainForm.AddCommand(write);

            WriteReaderIntervalTime_Parameter intervalPar = new WriteReaderIntervalTime_Parameter();
            if (cmbInterval.SelectedIndex == cmbInterval.Items.Count - 1)
            {
                intervalPar.IntervalTime = 65535;
            }
            else
            {
                intervalPar.IntervalTime = (ushort)cmbInterval.SelectedIndex;
            }

            WriteReaderIntervalTime writeInterval = new WriteReaderIntervalTime(cmdDtl, intervalPar);
            mMainForm.AddCommand(writeInterval);
            /*
            if (cBoxDoor1.Checked)
            {
                door = 1;
                WriteReaderInterval_Parameter par = new WriteReaderInterval_Parameter(door, use, detectionMode);
                WriteReaderInterval write = new WriteReaderInterval(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor2.Checked)
            {
                door = 2;
                WriteReaderInterval_Parameter par = new WriteReaderInterval_Parameter(door, use, detectionMode);
                WriteReaderInterval write = new WriteReaderInterval(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor3.Checked)
            {
                door = 3;
                WriteReaderInterval_Parameter par = new WriteReaderInterval_Parameter(door, use, detectionMode);
                WriteReaderInterval write = new WriteReaderInterval(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            if (cBoxDoor4.Checked)
            {
                door = 4;
                WriteReaderInterval_Parameter par = new WriteReaderInterval_Parameter(door, use, detectionMode);
                WriteReaderInterval write = new WriteReaderInterval(cmdDtl, par);
                mMainForm.AddCommand(write);
            }
            */
        }
        #endregion



        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
                return;
            object ex = this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value;
            if (e.ColumnIndex == 0 && e.RowIndex % 8 != 0 && ex == null)
            {
                return;
            }
            if (e.ColumnIndex == 0)
            {
                string isEx = ex.ToString();
                //收缩
                if (this.dataGridView1.Columns[e.ColumnIndex].Name == "EX" && isEx == "true")
                {
                    for (int i = 1; i <= 8; i++)
                    {
                        //隐藏行
                        this.dataGridView1.Rows[e.RowIndex + i].Visible = false;
                    }
                    //将IsEx设置为false，标明该节点已经收缩
                    this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value = "false";
                    this.dataGridView1.Rows[e.RowIndex].Cells["EX"].Value = "+";
                }
                else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "EX" && isEx == "false")
                {
                    for (int i = 1; i <= 8; i++)
                    {
                        this.dataGridView1.Rows[e.RowIndex + i].Visible = true;
                    }
                    this.dataGridView1.Rows[e.RowIndex].Cells["IsEx"].Value = "true";
                    this.dataGridView1.Rows[e.RowIndex].Cells["EX"].Value = "-";
                }
            }
            if (e.ColumnIndex >= 5 && e.ColumnIndex <= 8 && ex == null)
            {

                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if ((bool)cell.FormattedValue)
                {
                    cell.Value = false;
                    cell.EditingCellFormattedValue = false;
                }
                else
                {
                    //for (int i = 5; i <= 8; i++)
                    //{
                    //    DataGridViewCheckBoxCell allcell = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[i];
                    //    allcell.Value = false;
                    //    allcell.EditingCellFormattedValue = false;
                    //}
                    cell.Value = true;
                    cell.EditingCellFormattedValue = true;
                }
            }
            if (e.ColumnIndex >= 3 && e.ColumnIndex <= 4)
            {
                DataGridViewTextBoxColumn textbox = dataGridView1.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                if (textbox != null) //如果该列是TextBox列
                {
                    dataGridView1.BeginEdit(true); //开始编辑状态
                    dataGridView1.ReadOnly = false;
                }

            }
            else
            {
                dataGridView1.BeginEdit(false); //开始编辑状态
                dataGridView1.ReadOnly = true;
            }
        }

        private void DataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
                return;
            object ex = this.dataGridView2.Rows[e.RowIndex].Cells["IsEx2"].Value;
            if (e.ColumnIndex == 0 && e.RowIndex % 8 != 0 && ex == null)
            {
                return;
            }
            if (e.ColumnIndex == 0)
            {
                string isEx = ex.ToString();
                //收缩
                if (this.dataGridView2.Columns[e.ColumnIndex].Name == "EX2" && isEx == "true")
                {
                    for (int i = 1; i <= 8; i++)
                    {
                        //隐藏行
                        this.dataGridView2.Rows[e.RowIndex + i].Visible = false;
                    }
                    //将IsEx设置为false，标明该节点已经收缩
                    this.dataGridView2.Rows[e.RowIndex].Cells["IsEx2"].Value = "false";
                    this.dataGridView2.Rows[e.RowIndex].Cells["EX2"].Value = "+";
                }
                else if (this.dataGridView2.Columns[e.ColumnIndex].Name == "EX2" && isEx == "false")
                {
                    for (int i = 1; i <= 8; i++)
                    {
                        this.dataGridView2.Rows[e.RowIndex + i].Visible = true;
                    }
                    this.dataGridView2.Rows[e.RowIndex].Cells["IsEx2"].Value = "true";
                    this.dataGridView2.Rows[e.RowIndex].Cells["EX2"].Value = "-";
                }
            }

            if (e.ColumnIndex >= 3 && e.ColumnIndex <= 4)
            {
                DataGridViewTextBoxColumn textbox = dataGridView2.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                if (textbox != null) //如果该列是TextBox列
                {
                    dataGridView2.BeginEdit(true); //开始编辑状态
                    dataGridView2.ReadOnly = false;
                }

            }
            else
            {
                dataGridView2.BeginEdit(false); //开始编辑状态
                dataGridView2.ReadOnly = true;
            }
        }

        /// <summary>
        /// 读取防潜回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnReadAntiPassback_Click(object sender, EventArgs e)
        {
            var cmdDtl1 = mMainForm.GetCommandDetail();
            if (cmdDtl1 == null) return;
            var cmd0 = new ReadCheckInOut(cmdDtl1);
            mMainForm.AddCommand(cmd0);
            cmdDtl1.CommandCompleteEvent += (sdr, cmde) =>
            {
                if (cmde.Command.getResult() is ReadCheckInOut_Result readCheckInOut_Result)
                {
                    Invoke(() =>
                    {
                        rBtnCheckInOut1.Checked = readCheckInOut_Result.Mode == 1;
                        rBtnCheckInOut2.Checked = readCheckInOut_Result.Mode == 2;
                        mMainForm.AddCmdLog(cmde, $"{GetLanguage("groupBox13")}:{(rBtnCheckInOut1.Checked ? rBtnCheckInOut1.Text : rBtnCheckInOut2.Text)}");
                    });
                }
            };
            ForCheckBoxDoorNum((doorNum) =>
              {
                  byte door = (byte)doorNum;
                  var cmdDtl = mMainForm.GetCommandDetail();
                  if (cmdDtl == null) return;
                  ReadAntiPassback cmd = new ReadAntiPassback(cmdDtl, new DoorPort_Parameter(door));
                  mMainForm.AddCommand(cmd);
                  cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
                  {
                      if (cmde.Command.getResult() is AntiPassback_Result antiPassback_Result)
                      {
                          Invoke(() =>
                          {
                              rBtnAnti.Checked = antiPassback_Result.Use;
                              rBtnNotAnti.Checked = !antiPassback_Result.Use;
                              mMainForm.AddCmdLog(cmde, $"{GetLanguage("label22")} {antiPassback_Result.DoorNum}，{GetLanguage("groupBox13")}:{(rBtnAnti.Checked ? rBtnAnti.Text : rBtnNotAnti.Text)}");
                          });
                      }
                  };
              });
        }

        /// <summary>
        /// 写入防潜回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteAntiPassback_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            var writeCheckInOut_Parameter = new WriteCheckInOut_Parameter
            {
                Mode = (byte)(rBtnCheckInOut1.Checked ? 1 : 2)
            };
            var cmd0 = new WriteCheckInOut(cmdDtl, writeCheckInOut_Parameter);
            mMainForm.AddCommand(cmd0);
            var use = rBtnAnti.Checked;
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                var writeAntiPassback_Parameter = new WriteAntiPassback_Parameter(door, use);
                var cmd = new WriteAntiPassback(cmdDtl, writeAntiPassback_Parameter);
                mMainForm.AddCommand(cmd);
            });

        }

        #region 出门开关
        private void BtnReadPushButton_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                ReadPushButtonSetting cmd = new ReadPushButtonSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                PushButtonSetting_Result result = cmde.Command.getResult() as PushButtonSetting_Result;
                Invoke(() =>
                {

                    cbNormallyOpen.Checked = result.NormallyOpen;
                    cbReadPushButton.Checked = result.Use;
                    WeekTimeGroupPushButtonDto = result.weekTimeGroup;
                    SetAllTimePicker(tableLayoutPanel19, "beginTP", "EndTP", WeekTimeGroupPushButtonDto.GetItem(0));
                    for (int i = 0; i < 7; i++)
                    {
                        mMainForm.AddCmdLog(cmde, ShowDoorDayTimeGroup(GetWeekStr(i), WeekTimeGroupPushButtonDto.GetItem(i)));
                    }
                    var log = $"{GetLanguage("label22")}:{result.DoorNum}{Environment.NewLine}";
                    log += $"{GetLanguage("groupBox14")}:{(result.Use ? GetLanguage("Msg6") : GetLanguage("Msg2"))}{Environment.NewLine}";
                    log += $"{GetLanguage("cbNormallyOpen")}:{(result.NormallyOpen ? GetLanguage("Msg6") : GetLanguage("Msg2"))}";
                    mMainForm.AddCmdLog(cmde, log);
                });
            };
        }

        private void BtnWritePushButton_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)doorNum;
                WritePushButtonSetting_Parameter par = new WritePushButtonSetting_Parameter(door,
                    cbReadPushButton.Checked,
                    cbNormallyOpen.Checked,
                    WeekTimeGroupPushButtonDto);
                WritePushButtonSetting cmd = new WritePushButtonSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }

        private void CmbPushButtonWeekday_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (WeekTimeGroupPushButtonDto != null)
            {
                var day = WeekTimeGroupPushButtonDto.GetItem(cmbPushButtonWeekday.SelectedIndex);
                SetAllTimePicker(tableLayoutPanel19, "beginTP", "EndTP", day);
            }
        }
        private void CbReadPushButton_CheckedChanged(object sender, EventArgs e)
        {
            plPushButton.Visible = cbReadPushButton.Checked;

            cbNormallyOpen.Visible = cbReadPushButton.Checked;
        }
        #endregion

        private void BeginTP_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupPushButtonDto, cmbPushButtonWeekday.SelectedIndex, int.Parse(dtp.Name.Substring(7)) - 1, 1, dtp.Value);
        }


        private void EndTP_ValueChanged(object sender, EventArgs e)
        {
            DateTimePicker dtp = sender as DateTimePicker;
            SetWeekTimeGroupValue(WeekTimeGroupPushButtonDto, cmbPushButtonWeekday.SelectedIndex, int.Parse(dtp.Name.Substring(5)) - 1, 2, dtp.Value);
        }

        #region 全卡开门
        private void BtnReadAnyCard_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum((doorNum) =>
            {
                byte door = (byte)(doorNum);
                ReadAnyCardSetting cmd = new ReadAnyCardSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                AnyCardSetting_Result result = cmde.Command.getResult() as AnyCardSetting_Result;
                Invoke(() =>
                {
                    cbAnyCardAuto.Checked = result.AutoSave;
                    cbAnyCardUse.Checked = result.Use;
                    cmbAnyCardTimeGroup.SelectedIndex = (result.TimeGroup - 1);
                });
                StringBuilder sb = new StringBuilder();
                var use = result.Use ? enabled : disabled;
                var autoSave = result.AutoSave ? enabled : disabled;
                sb.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                sb.AppendLine($"{GetLanguage("groupBox15")}:{use}");
                sb.AppendLine($"{cbAnyCardAuto.Text}:{autoSave}");
                if (result.AutoSave)
                    sb.AppendLine($"{label44.Text}[{result.TimeGroup}]{label63.Text}");
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }

        private void BtnWriteAnyCard_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new WriteAnyCardSetting_Parameter(door,
                    cbAnyCardUse.Checked,
                    cbAnyCardAuto.Checked,
                    cmbAnyCardTimeGroup.SelectedIndex + 1);
                var cmd = new WriteAnyCardSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }


        #endregion

        #region 设置语音播报功能
        private void BtnReadVoiceBroadcastSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                ReadVoiceBroadcastSetting cmd = new ReadVoiceBroadcastSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                var result = cmde.Command.getResult() as VoiceBroadcastSetting_Result;
                Invoke(() =>
                {
                    cbVoiceBroadcastSettingUse.Checked = result.Use;
                });
                var sb = new StringBuilder();
                sb.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                sb.AppendLine($"{groupBox17.Text}:{(result.Use ? enabled : disabled)}");
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }

        private void BtnWriteWriteVoiceBroadcastSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new WriteVoiceBroadcastSetting_Parameter(door, cbVoiceBroadcastSettingUse.Checked);
                var cmd = new WriteVoiceBroadcastSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });



        }
        #endregion

        #region 门内外同时读卡开门
        private void BtnReadInOutSideReadOpenSetting_Click(object sender, EventArgs e)
        {
            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var cmd = new ReadInOutSideReadOpenSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                var result = cmde.Command.getResult() as InOutSideReadOpenSetting_Result;
                Invoke(() =>
                {
                    cbInOutSideReadOpenSettingUse.Checked = result.Use;
                });
                var sb = new StringBuilder();
                sb.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                sb.AppendLine($"{groupBox18.Text}:{(result.Use ? enabled : disabled)}");
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }

        private void BtnWriteInOutSideReadOpenSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new InOutSideReadOpenSetting_Parameter(door, cbInOutSideReadOpenSettingUse.Checked);
                var cmd = new WriteInOutSideReadOpenSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }

        #endregion

        #region 键盘管理功能


        private void BtnReadManageKeyboardSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var cmd = new ReadManageKeyboardSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });

            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                WriteManageKeyboardSetting_Parameter result = cmde.Command.getResult() as WriteManageKeyboardSetting_Parameter;
                Invoke(() =>
                {
                    cbManageKeyboardSettingUse.Checked = result.Use;
                    txtPassword.Text = result.Password;
                });
                var sb = new StringBuilder();
                sb.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                sb.AppendLine($"{groupBox19.Text}:{(result.Use ? enabled : disabled)}");
                sb.AppendLine($"{label64.Text}{result.Password}");
                mMainForm.AddCmdLog(cmde, sb.ToString());
            };
        }

        private void BtnWriteManageKeyboardSetting_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text.Trim().Length < 4)
            {
                MessageBox.Show(GetLanguage("Msg50"));
                return;
            }
            string pattern = @"\b(0[xX])?[A-Fa-f0-9]+\b";
            bool isHexNum = Regex.IsMatch(txtPassword.Text.Trim(), pattern);
            if (!isHexNum)
            {
                MessageBox.Show(GetLanguage("Msg51"));
                return;
            }
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new WriteManageKeyboardSetting_Parameter(door,
                    cbManageKeyboardSettingUse.Checked,
                    txtPassword.Text.Trim());
                var cmd = new WriteManageKeyboardSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }
        #endregion

        #region 区域防潜回
        private void CbAreaAntiPassbackUse_CheckedChanged(object sender, EventArgs e)
        {
            //  plAreaAntiPassback.Visible = cbAreaAntiPassbackUse.Checked;
            lbPort.Visible = lbSN.Visible = lbIP.Visible = txtIP.Visible = txtPort.Visible = txtSN.Visible = (cmbAreaType.SelectedIndex == 1 && cbAreaAntiPassbackUse.Checked);
        }

        private void BtnReadAreaAntiPassback_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                ReadAreaAntiPassback cmd = new ReadAreaAntiPassback(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });

            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                var result = cmde.Command.getResult() as AreaAntiPassback_Result;
                Invoke(() =>
                {
                    cbAreaAntiPassbackUse.Checked = result.Use;
                    txtSN.Text = result.SN;
                    txtPort.Text = result.Port.ToString();
                    byte[] listb = result.IP;

                    txtIP.Text = listb[0] + "." + listb[1] + "." + listb[2] + "." + listb[3];
                    cmbAreaType.SelectedIndex = result.Type ? 0 : 1;
                    var log = new StringBuilder();
                    log.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                    log.AppendLine($"{groupBox20.Text}:{(result.Use ? enabled : disabled)}");
                    if (result.Use)
                    {
                        log.AppendLine($"{label66.Text}:{cmbAreaType.Text}");
                        log.AppendLine($"{lbSN.Text}:{result.SN}");
                        log.AppendLine($"{lbIP.Text}:{txtIP.Text}");
                        log.AppendLine($"{lbPort.Text}:{result.Port}");
                    }
                    mMainForm.AddCmdLog(cmde, log.ToString());
                });

            };
        }

        private void BtnWriteAreaAntiPassback_Click(object sender, EventArgs e)
        {
            string pattern = @"^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$";
            bool isHexNum = Regex.IsMatch(txtIP.Text.Trim(), pattern);
            if (!isHexNum)
            {
                MessageBox.Show(GetLanguage("Msg52"));
                return;
            }
            ushort s = 0;
            if (!ushort.TryParse(txtPort.Text.Trim(), out s))
            {
                MessageBox.Show(GetLanguage("Msg53"));
                return;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            byte[] bIP = new byte[4];
            string[] listip = txtIP.Text.Trim().Split('.');
            for (int i = 0; i < listip.Length; i++)
            {
                bIP[i] = byte.Parse(listip[i]);
            }
            var port = ushort.Parse(txtPort.Text.Trim());
            var sn = txtSN.Text.Trim();
            var type = cmbAreaType.SelectedIndex == 0;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new WriteAreaAntiPassback_Parameter(door,
                    cbAreaAntiPassbackUse.Checked, type, sn, bIP, port);
                var cmd = new WriteAreaAntiPassback(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });

        }

        private void CmbAreaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbPort.Visible = lbSN.Visible = lbIP.Visible = txtIP.Visible = txtPort.Visible = txtSN.Visible = (cmbAreaType.SelectedIndex == 1 && cbAreaAntiPassbackUse.Checked);
        }
        #endregion

        #region 区域互锁
        private void CbInterLockSettingUse_CheckedChanged(object sender, EventArgs e)
        {
            //lbAreaType2.Visible = cmbInterLockSettingAreaType.Visible = cbInterLockSettingUse.Checked;
            lbPort2.Visible = lbIP2.Visible = lbAreaType2.Visible = lbNum2.Visible = lbAreaCode.Visible =
            cmbNum.Visible = txtInterLockSettingIP.Visible = txtInterLockSettingPort.Visible = cmbInterLockSettingAreaType.Visible = txtAreaCode.Visible =
               cbInterLockSettingUse.Checked;
        }

        private void BtnReadInterLockSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                ReadInterLockSetting cmd = new ReadInterLockSetting(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            var enabled = GetLanguage("Msg6");
            var disabled = GetLanguage("Msg2");
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                var result = cmde.Command.getResult() as InterLockSetting_Result;
                Invoke(() =>
                {
                    cbInterLockSettingUse.Checked = result.Use;
                    cmbNum.SelectedIndex = result.Num - 1;
                    txtInterLockSettingPort.Text = result.Port.ToString();
                    byte[] listb = result.IP;
                    txtAreaCode.Text = result.AreaCode.ToString();
                    txtInterLockSettingIP.Text = listb[0] + "." + listb[1] + "." + listb[2] + "." + listb[3];
                    cmbInterLockSettingAreaType.SelectedIndex = result.Type ? 0 : 1;

                    var log = new StringBuilder();
                    log.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                    log.AppendLine($"{groupBox21.Text}:{(result.Use ? enabled : disabled)}");
                    if (result.Use)
                    {
                        log.AppendLine($"{lbAreaType2.Text}:{cmbInterLockSettingAreaType.Text}");
                        log.AppendLine($"{lbAreaCode.Text}:{result.AreaCode.ToString()}");
                        log.AppendLine($"{lbNum2.Text}:{cmbNum.Text}");
                        log.AppendLine($"{lbIP2.Text}:{txtInterLockSettingIP.Text}");
                        log.AppendLine($"{lbPort2.Text}:{txtInterLockSettingPort.Text}");
                    }
                    mMainForm.AddCmdLog(cmde, log.ToString());
                });

            };
        }

        private void BtnWriteInterLockSetting_Click(object sender, EventArgs e)
        {
            string pattern = @"^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$";
            bool isHexNum = Regex.IsMatch(txtInterLockSettingIP.Text.Trim(), pattern);
            if (!isHexNum)
            {
                MessageBox.Show(GetLanguage("Msg52"));
                return;
            }
            if (!ushort.TryParse(txtInterLockSettingPort.Text.Trim(), out ushort s))
            {
                MessageBox.Show(GetLanguage("Msg53"));
                return;
            }
            if (!int.TryParse(txtAreaCode.Text.Trim(), out int iOut))
            {
                MessageBox.Show(GetLanguage("Msg54"));
                return;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            byte[] bIP = new byte[4];
            string[] listip = txtInterLockSettingIP.Text.Trim().Split('.');
            for (int i = 0; i < listip.Length; i++)
            {
                bIP[i] = byte.Parse(listip[i]);
            }
            var areaCode = int.Parse(txtAreaCode.Text.Trim());
            var type = cmbInterLockSettingAreaType.SelectedIndex == 0;
            var num = Convert.ToByte(cmbNum.SelectedIndex + 1);
            var port = ushort.Parse(txtInterLockSettingPort.Text.Trim());
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                var par = new WriteInterLockSetting_Parameter(door,
                    cbInterLockSettingUse.Checked, type, areaCode, num, bIP, port);
                var cmd = new WriteInterLockSetting(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });
        }

        private void CmbInterLockSettingAreaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbPort2.Visible = lbIP2.Visible = lbNum2.Visible = lbAreaCode.Visible =
           cmbNum.Visible = txtInterLockSettingIP.Visible = txtInterLockSettingPort.Visible = txtAreaCode.Visible =
              (cmbInterLockSettingAreaType.SelectedIndex == 1 && cbInterLockSettingUse.Checked);
        }

        #endregion

        #region 多卡开门检测模式参数
        private void BtnReadManyCardOpenMode_Click(object sender, EventArgs e)
        {
            byte door = (byte)(1);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            var protocolType = mMainForm.GetProtocolType();
            ReadMultiCard cmd = null;
            if (protocolType == CommandDetailFactory.ControllerType.Door88)
            {
                cmd = new ReadMultiCard(cmdDtl, new ReadMultiCard_Parameter(1, false));
            }
            else if (CheckProtocolTypeIs89H())
            {
                cmd = new Door89H.Door.MultiCard.ReadMultiCard(cmdDtl, new ReadMultiCard_Parameter(1, false));
            }
            else if (protocolType == CommandDetailFactory.ControllerType.Door58)
            {
                cmd = new Door89H.Door.MultiCard.ReadMultiCard(cmdDtl, new ReadMultiCard_Parameter(1, true));
            }
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                MultiCard_Result result = cmde.Command.getResult() as MultiCard_Result;
                Invoke(() =>
                {
                    cmbManyCardOpenMode.SelectedIndex = result.ReaderWaitMode;
                    cmbAntiPassback.SelectedIndex = result.AntiPassback;
                    cmbVerifyType.SelectedIndex = result.VerifyType;
                    txtAGroupCount.Text = result.AGroupCount.ToString();
                    txtBGroupCount.Text = result.BGroupCount.ToString();
                    var log = new StringBuilder();
                    if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg4"))
                    {
                        var groups = GetLanguage("cmbGroupType").Split(',');
                        listGroupA = result.GroupA;
                        listGroupB = result.GroupB;
                        log.AppendLine(GetGourpLog(result.GroupA, groups[0]));
                        log.AppendLine(GetGourpLog(result.GroupB, groups[1]));
                        mMainForm.AddCmdLog(cmde, log.ToString());
                        log.Clear();
                    }
                    else if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg3"))
                    {
                        listFix = result.GroupFix;
                        log.AppendLine(GetGroupFixLog(result.GroupFix));
                        mMainForm.AddCmdLog(cmde, log.ToString());
                        log.Clear();
                    }
                    CmbVerifyType_SelectedIndexChanged(null, null);
                    CmbGroupNum_SelectedIndexChanged(null, null);

                    log.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                    log.AppendLine($"{label67.Text}:{cmbManyCardOpenMode.Text}");
                    log.AppendLine($"{label68.Text}:{cmbAntiPassback.Text}");
                    log.AppendLine($"{label69.Text}:{cmbVerifyType.Text}");
                    log.AppendLine($"{label71.Text}:{txtAGroupCount.Text}");
                    log.AppendLine($"{label72.Text}:{txtBGroupCount.Text}");
                    mMainForm.AddCmdLog(cmde, log.ToString());
                });
            };
        }
        private string GetGourpLog(List<List<decimal>> groups, string groupName)
        {
            var log = new StringBuilder();
            for (int i = 0; i < groups.Count; i++)
            {
                log.AppendLine($"{groupName}:{(i + 1)}");
                var group = groups[i];
                log.AppendLine($"{GetLanguage("Msg61")}:{group.Count}");

                for (int j = 0; j < group.Count; j++)
                {
                    log.Append($"{group[j]}(0x{((ulong)group[j]):x6}) ;");
                }
                log.AppendLine();
            }
            return log.ToString();
        }

        private string GetGroupFixLog(List<MultiCard_GroupFix> GroupFix)
        {
            var tyepKeys = GetLanguage("Cmb_InOutType").Split(',');
            var log = new StringBuilder();
            foreach (var item in GroupFix)
            {
                log.AppendLine($"{label1.Text}{tyepKeys[item.GroupType]}");
                log.AppendLine($"{GetLanguage("Msg61")}:{item.CardList.Count}");
                for (int j = 0; j < item.CardList.Count; j++)
                {
                    log.Append($"{item.CardList[j]}(0x{((ulong)item.CardList[j]):x6}) ;");
                }
                log.AppendLine();
            }
            return log.ToString();
        }
        /// <summary>
        /// 写入多门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteManyCardOpenMode_Click(object sender, EventArgs e)
        {
            byte bAcount = 0;
            byte bBcount = 0;
            if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg4"))
            {
                if (!byte.TryParse(txtAGroupCount.Text, out bAcount))
                {
                    MessageBox.Show(GetLanguage("Msg55"));
                    return;
                }
                if (!byte.TryParse(txtBGroupCount.Text, out bBcount))
                {
                    MessageBox.Show(GetLanguage("Msg56"));
                    return;
                }
            }


            byte door = (byte)(1);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            var protocolType = mMainForm.GetProtocolType();


            if (protocolType == CommandDetailFactory.ControllerType.Door88)
            {
                WriteMultiCard_Parameter par = new WriteMultiCard_Parameter(door, (byte)cmbManyCardOpenMode.SelectedIndex, (byte)cmbAntiPassback.SelectedIndex
                    , (byte)cmbVerifyType.SelectedIndex, bAcount, bBcount
                    , listGroupA, listGroupB, listFix);
                WriteMultiCard cmd = new WriteMultiCard(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            }
            else if (CheckProtocolTypeIs89H())
            {
                Door89H.Door.MultiCard.WriteMultiCard_Parameter par = new Door89H.Door.MultiCard.WriteMultiCard_Parameter(door, (byte)cmbManyCardOpenMode.SelectedIndex, (byte)cmbAntiPassback.SelectedIndex, (byte)cmbVerifyType.SelectedIndex
                        , bAcount, bBcount
                        , listGroupA, listGroupB, listFix);
                Door89H.Door.MultiCard.WriteMultiCard cmd = new Door89H.Door.MultiCard.WriteMultiCard(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            }
            else if (protocolType == CommandDetailFactory.ControllerType.Door58)
            {
                WriteMultiCard_Parameter par = new WriteMultiCard_Parameter(door, (byte)cmbManyCardOpenMode.SelectedIndex, (byte)cmbAntiPassback.SelectedIndex, listFix);
                WriteMultiCard cmd = new WriteMultiCard(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            }
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
            };
        }
        #endregion

        #region 多卡开门验证方式
        private void CmbVerifyType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var ab = GetLanguage("Msg4");
            // plManyCardOpenVerify.Visible = cmbVerifyType.SelectedItem.ToString() == ab;
            plMutiCard.Visible = cmbVerifyType.SelectedItem.ToString() == ab;
            if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg3"))
            {
                dataGridView5.Visible = true;
                plMutiCard.Visible = true;

                cmbGroupNum.Items.Clear();
                int count = 8;

                string[] array = new string[count];
                for (int i = 1; i <= count; i++)
                {
                    array[i - 1] = i.ToString();
                }
                cmbGroupNum.Items.AddRange(array);
                cmbGroupNum.SelectedIndex = 0;

                lbgrouptype.Visible = false;
                cmbGroupType.Visible = false;
                dataGridView3.Visible = false;
                dataGridView4.Visible = false;
                dataGridView5.Visible = true;
                label1.Visible = true;
                Cmb_InOutType.Visible = true;
            }

            if (cmbVerifyType.SelectedItem.ToString() == ab)
            {
                dataGridView3.Visible = true;
                dataGridView5.Visible = false;
                label1.Visible = false;
                Cmb_InOutType.Visible = false;
                cmbGroupNum.Items.Clear();
                int count = 5;

                string[] array = new string[count];
                for (int i = 1; i <= count; i++)
                {
                    array[i - 1] = i.ToString();
                }
                cmbGroupNum.Items.AddRange(array);
                cmbGroupNum.SelectedIndex = 0;
            }
        }



        #endregion

        #region 多卡开门AB组设置

        private void CmbGroupType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!CheckProtocolTypeIs89H())
            {
                return;
            }
            cmbGroupNum.Items.Clear();
            int count = 5;
            if (cmbGroupType.SelectedIndex == 1)
            {
                count = 20;
            }
            string[] array = new string[count];
            for (int i = 1; i <= count; i++)
            {
                array[i - 1] = i.ToString();
            }
            cmbGroupNum.Items.AddRange(array);
            cmbGroupNum.SelectedIndex = 0;
            //CmbGroupNum_SelectedIndexChanged(null, null);


        }

        private void InitCardDataList()
        {

            dataGridView3.AutoGenerateColumns = false;
            dataGridView4.AutoGenerateColumns = false;
            dataGridView5.AutoGenerateColumns = false;
            dataGridView4.Visible = false;
            dataGridView5.Visible = false;

            listGroupA = new List<List<decimal>>(5);
            listGroupB = new List<List<decimal>>(20);
            listFix = new List<MultiCard_GroupFix>(10);
            /**/
            for (int i = 0; i < 5; i++)
            {
                listGroupA.Add(new List<decimal>());

                for (int j = 1; j <= 50; j++)
                {
                    listGroupA[i].Add(0);
                }

            }
            for (int i = 0; i < 20; i++)
            {
                listGroupB.Add(new List<decimal>());

                for (int j = 1; j <= 100; j++)
                {
                    listGroupB[i].Add(0);
                }
            }

            for (int i = 1; i <= 10; i++)
            {
                MultiCard_GroupFix groupFix = new MultiCard_GroupFix();
                groupFix.GroupType = 1;
                groupFix.CardList = new List<decimal>();
                for (int j = 1; j <= 8; j++)
                {
                    groupFix.CardList.Add((decimal)(100000 + j));
                }
                listFix.Add(groupFix);
            }
        }

        private void CbConvertHex_CheckedChanged(object sender, EventArgs e)
        {
            /*
            //10 转 16
            if (cbConvertHex.Checked)
            {
                for (int i = 0; i < listGroupA.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listGroupA[i].Card))
                    {
                        listGroupA[i].Card = int.Parse(listGroupA[i].Card).ToString("X");
                    }
                    
                }
                for (int i = 0; i < listGroupB.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listGroupB[i].Card))
                    {
                        listGroupB[i].Card = int.Parse(listGroupB[i].Card).ToString("X");
                    }
                    
                }
                for (int i = 0; i < listFix.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listFix[i].Card))
                    {
                        listFix[i].Card = int.Parse(listFix[i].Card).ToString("X");
                    }
                }
            }//16 转 10
            else
            {
                for (int i = 0; i < listGroupA.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listGroupA[i].Card))
                        listGroupA[i].Card = Convert.ToInt32(listGroupA[i].Card, 16).ToString();
                }
                for (int i = 0; i < listGroupB.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listGroupB[i].Card))
                        listGroupB[i].Card = Convert.ToInt32(listGroupB[i].Card,16).ToString();
                }
                for (int i = 0; i < listFix.Count; i++)
                {
                    if (!string.IsNullOrEmpty(listFix[i].Card))
                        listFix[i].Card = Convert.ToInt32(listFix[i].Card, 16).ToString();
                }
            }
            CmbGroupNum_SelectedIndexChanged(null, null);
            */
        }

        private void BtnAutoFill_Click(object sender, EventArgs e)
        {
            //if (cmbVerifyType.SelectedItem.ToString() == "AB组合")
            {
                listGroupA.Clear();
                for (int i = 1; i <= 5; i++)
                {
                    List<decimal> list = new List<decimal>();
                    for (int j = 1; j <= 50; j++)
                    {
                        list.Add((decimal)(100 * i + j));
                    }
                    listGroupA.Add(list);
                }
                listGroupB.Clear();
                for (int i = 1; i <= 20; i++)
                {
                    List<decimal> list = new List<decimal>();
                    for (int j = 1; j <= 100; j++)
                    {
                        list.Add((decimal)(1000 * i + j));
                    }
                    listGroupB.Add(list);
                }
            }
            //else if (cmbVerifyType.SelectedItem.ToString() == "固定组合")
            {
                listFix.Clear();
                for (int i = 1; i <= 10; i++)
                {
                    MultiCard_GroupFix groupFix = new MultiCard_GroupFix();
                    groupFix.GroupType = 1;
                    groupFix.CardList = new List<decimal>();
                    for (int j = 1; j <= 8; j++)
                    {
                        groupFix.CardList.Add((ulong)(i * 100000 + j));
                    }
                    listFix.Add(groupFix);
                }
            }
            CmbGroupNum_SelectedIndexChanged(null, null);
        }

        private void CmbGroupNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (mMainForm.GetProtocolType().Contains("Door58"))
            //{
            //    return;
            //}
            if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg4"))
            {
                if (cmbGroupType.SelectedIndex == 0)
                {
                    dataGridView3.Rows.Clear();
                    //dataGridView3.DataSource = new BindingList<CardData>(listGroupA.Skip(cmbGroupNum.SelectedIndex * 50).Take(50).ToArray());
                    var list = listGroupA[cmbGroupNum.SelectedIndex];
                    for (int i = 1; i <= 50; i++)
                    {
                        int index = this.dataGridView3.Rows.Add();
                        this.dataGridView3.Rows[index].Cells[0].Value = i.ToString().PadLeft(2, '0');
                        if (i > list.Count)
                        {
                            this.dataGridView3.Rows[index].Cells[1].Value = "";
                        }
                        else
                        {
                            this.dataGridView3.Rows[index].Cells[1].Value = list[i - 1].ToString();
                        }
                    }
                    dataGridView3.Visible = true;
                    dataGridView4.Visible = false;
                    dataGridView5.Visible = false;
                }
                else if (cmbGroupType.SelectedIndex == 1)
                {
                    dataGridView4.Rows.Clear();
                    //dataGridView3.DataSource = new BindingList<CardData>(listGroupA.Skip(cmbGroupNum.SelectedIndex * 50).Take(50).ToArray());
                    var list = listGroupB[cmbGroupNum.SelectedIndex];
                    for (int i = 1; i <= 100; i++)
                    {
                        int index = this.dataGridView4.Rows.Add();
                        this.dataGridView4.Rows[index].Cells[0].Value = i.ToString().PadLeft(2, '0');
                        if (i > list.Count)
                        {
                            this.dataGridView4.Rows[index].Cells[1].Value = "";
                        }
                        else
                        {
                            this.dataGridView4.Rows[index].Cells[1].Value = list[i - 1].ToString();
                        }
                    }
                    dataGridView4.Visible = true;
                    dataGridView3.Visible = false;
                    dataGridView5.Visible = false;
                }
            }

            if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg3"))
            {
                dataGridView5.Rows.Clear();
                //dataGridView3.DataSource = new BindingList<CardData>(listGroupA.Skip(cmbGroupNum.SelectedIndex * 50).Take(50).ToArray());
                var list = listFix[cmbGroupNum.SelectedIndex].CardList;
                for (int i = 1; i <= 8; i++)
                {
                    int index = this.dataGridView5.Rows.Add();
                    this.dataGridView5.Rows[index].Cells[0].Value = i.ToString().PadLeft(2, '0');
                    if (i > list.Count)
                    {
                        this.dataGridView5.Rows[index].Cells[1].Value = "";
                    }
                    else
                    {
                        this.dataGridView5.Rows[index].Cells[1].Value = list[i - 1].ToString();
                    }
                }
                dataGridView5.Visible = true;
                dataGridView3.Visible = false;
                dataGridView4.Visible = false;
            }
        }
        private void DataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                DataGridViewTextBoxColumn textbox = dataGridView3.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                if (textbox != null) //如果该列是TextBox列
                {
                    dataGridView3.BeginEdit(true); //开始编辑状态
                    dataGridView3.ReadOnly = false;
                }
            }
            else
            {
                dataGridView3.BeginEdit(false); //开始编辑状态
                dataGridView3.ReadOnly = true;
            }
        }

        private void DataGridView4_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                DataGridViewTextBoxColumn textbox = dataGridView4.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                if (textbox != null) //如果该列是TextBox列
                {
                    dataGridView4.BeginEdit(true); //开始编辑状态
                    dataGridView4.ReadOnly = false;
                }
            }
            else
            {
                dataGridView4.BeginEdit(false); //开始编辑状态
                dataGridView4.ReadOnly = true;
            }
        }

        private void DataGridView3_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView3.CurrentCell.ColumnIndex == 1)
            {
                //e.CellStyle.BackColor = Color.FromName("window"); 
                //DataGridViewComboBoxEditingControl editingControl = e.Control as DataGridViewComboBoxEditingControl; 
                DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
                editingControl.TextChanged += (se, ea) =>
                {   //要判断类型
                    if (true)
                    {
                        listGroupA[cmbGroupNum.SelectedIndex][dataGridView3.CurrentCell.RowIndex] = Convert.ToUInt64(dataGridView3.CurrentCell.EditedFormattedValue.ToString());
                    }

                };
            }

        }

        private void DataGridView4_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView4.CurrentCell.ColumnIndex == 1)
            {
                //e.CellStyle.BackColor = Color.FromName("window"); 
                //DataGridViewComboBoxEditingControl editingControl = e.Control as DataGridViewComboBoxEditingControl; 
                DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
                editingControl.TextChanged += (se, ea) =>
                {
                    //listGroupB[dataGridView4.CurrentCell.RowIndex].Card = dataGridView4.CurrentCell.EditedFormattedValue.ToString();
                    if (true)
                    {
                        listGroupB[cmbGroupNum.SelectedIndex][dataGridView4.CurrentCell.RowIndex] = Convert.ToUInt64(dataGridView4.CurrentCell.EditedFormattedValue.ToString());
                    }
                };
            }
        }

        private void BtnDeleteGroup_Click(object sender, EventArgs e)
        {
            if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg4"))
            {
                if (cmbGroupType.SelectedIndex == 0)
                {
                    for (int i = 0; i < listGroupA.Count; i++)
                    {
                        for (int j = listGroupA[i].Count; j > 0; j--)
                        {
                            listGroupA[i].RemoveAt(j - 1);
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < listGroupB.Count; i++)
                    {
                        for (int j = listGroupB[i].Count; j > 0; j--)
                        {
                            listGroupB[i].RemoveAt(j - 1);
                        }
                    }
                }
            }
            else if (cmbVerifyType.SelectedItem.ToString() == GetLanguage("Msg3"))
            {
                for (int i = 0; i < listFix.Count; i++)
                {
                    for (int j = listFix[i].CardList.Count; j > 0; j--)
                    {
                        listFix[i].CardList.RemoveAt(j - 1);
                    }
                }
            }
            CmbGroupNum_SelectedIndexChanged(null, null);
        }

        #endregion

        private void DataGridView5_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                DataGridViewTextBoxColumn textbox = dataGridView5.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                if (textbox != null) //如果该列是TextBox列
                {
                    dataGridView5.BeginEdit(true); //开始编辑状态
                    dataGridView5.ReadOnly = false;
                }

            }
            else
            {
                dataGridView5.BeginEdit(false); //开始编辑状态
                dataGridView5.ReadOnly = true;
            }
        }

        private void DataGridView5_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView5.CurrentCell.ColumnIndex == 1)
            {
                DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
                editingControl.TextChanged += (se, ea) =>
                {
                    //listFix[dataGridView5.CurrentCell.RowIndex].Card = dataGridView5.CurrentCell.EditedFormattedValue.ToString();
                    if (true)
                    {
                        listFix[cmbGroupNum.SelectedIndex].CardList[dataGridView5.CurrentCell.RowIndex] = Convert.ToUInt64(dataGridView5.CurrentCell.EditedFormattedValue.ToString());
                    }
                };
            }
        }
        #region 读卡器防拆报警功能
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnReadReaderAlarm_Click(object sender, EventArgs e)
        {

            byte door = (byte)(1);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadReaderAlarm cmd = new ReadReaderAlarm(cmdDtl, new DoorPort_Parameter(1));
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReaderAlarm_Result result = cmde.Command.getResult() as ReaderAlarm_Result;
                Invoke(() =>
                {
                    cbReaderAlarmUse.Checked = result.Use == 1;
                });
                string tip2 = result.Use == 1 ? GetLanguage("Msg57") : GetLanguage("Msg58");
                mMainForm.AddCmdLog(cmde, $"{GetLanguage("Msg59")}{door}，{GetLanguage("Msg8")}：{result.Use}、{tip2}");
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnWriteReaderAlarm_Click(object sender, EventArgs e)
        {
            byte door = (byte)(1);
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteReaderAlarm_Parameter par = new WriteReaderAlarm_Parameter(door, (byte)(cbReaderAlarmUse.Checked ? 1 : 0));
            WriteReaderAlarm cmd = new WriteReaderAlarm(cmdDtl, par);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {

            };
        }

        #endregion

        private void BtnReadReadCardAndTakePictures_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                ReadReadCardAndTakePictures cmd = new ReadReadCardAndTakePictures(cmdDtl, new DoorPort_Parameter(door));
                mMainForm.AddCommand(cmd);
            });
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                var enabled = GetLanguage("Msg6");
                var disabled = GetLanguage("Msg2");
                ReadCardAndTakePictures_Result result = cmde.Command.getResult() as ReadCardAndTakePictures_Result;
                Invoke(() =>
                {
                    cbInDoorUse.Checked = result.InDoorUse;
                    cbOutDoorUse.Checked = result.OutDoorUse;

                    txtInDoorIP.Text = string.Join(".", result.InDoorIP.Select(t => t.ToString()));
                    txtOutDoorIP.Text = string.Join(".", result.OutDoorIP.Select(t => t.ToString()));

                    txtInDoorPort.Text = result.InDoorPort.ToString();
                    txtOutDoorPort.Text = result.OutDoorPort.ToString();

                    txtInDoorProtocol.Text = string.Join("", result.InDoorProtocol);
                    txtOutDoorProtocol.Text = string.Join("", result.OutDoorProtocol);
                    var log = new StringBuilder();
                    log.AppendLine($"{GetLanguage("label22")}:{result.DoorNum}");
                    log.AppendLine($"{label73.Text}:{(result.InDoorUse ? enabled : disabled)}");
                    log.AppendLine($"{label75.Text}:{txtInDoorIP.Text}");
                    log.AppendLine($"{label77.Text}:{txtInDoorPort.Text}");
                    log.AppendLine($"{label79.Text}:{txtInDoorProtocol.Text}");
                    log.AppendLine();
                    log.AppendLine($"{label74.Text}:{(result.InDoorUse ? enabled : disabled)}");
                    log.AppendLine($"{label76.Text}:{txtOutDoorIP.Text}");
                    log.AppendLine($"{label78.Text}:{txtOutDoorPort.Text}");
                    log.AppendLine($"{label80.Text}:{txtOutDoorProtocol.Text}");
                    mMainForm.AddCmdLog(cmde, log.ToString());
                });
            };
        }

        private void BtnWriteReadCardAndTakePictures_Click(object sender, EventArgs e)
        {
         
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;

            byte[] bIndoorIP = new byte[4];
            string sIP = txtInDoorIP.Text;
            if (TCPDetail.CheckIP(sIP))
            {
                string[] listip = sIP.Trim().Split('.');
                for (int i = 0; i < listip.Length; i++)
                {
                    bIndoorIP[i] = byte.Parse(listip[i]);
                }
            }
            else
            {
                MsgErr(GetLanguage("Msg60"));
                return;
            }


            byte[] bOutdoorIP = new byte[4];
            sIP = txtOutDoorIP.Text;
            if (TCPDetail.CheckIP(sIP))
            {
                string[] listip = sIP.Trim().Split('.');
                for (int i = 0; i < listip.Length; i++)
                {
                    bOutdoorIP[i] = byte.Parse(listip[i]);
                }
            }
            else
            {
                MsgErr(GetLanguage("Msg60"));
                return;
            }
            ForCheckBoxDoorNum(doorNum =>
            {
                byte door = (byte)doorNum;
                WriteReadCardAndTakePictures_Parameter par = new WriteReadCardAndTakePictures_Parameter(door, cbInDoorUse.Checked, bIndoorIP, ushort.Parse(txtInDoorPort.Text), txtInDoorProtocol.Text,
                    cbOutDoorUse.Checked, bOutdoorIP, ushort.Parse(txtOutDoorPort.Text), txtOutDoorProtocol.Text);
                WriteReadCardAndTakePictures cmd = new WriteReadCardAndTakePictures(cmdDtl, par);
                mMainForm.AddCommand(cmd);
            });


          
        }

        private void groupBox14_Enter(object sender, EventArgs e)
        {

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }
    }
}
